package com.ricky.mq.client.session;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ricky.mq.client.code.constant.ClientCommandCode;
import com.ricky.mq.client.code.handler.WaitOrSendMsgHandler;
import com.ricky.mq.client.message.data.CallbackData;
import com.ricky.mq.client.message.data.client.ClientMsgModelData;
import com.ricky.mq.client.message.data.server.ServerMsgModelData;
import com.ricky.mq.client.message.model.BoringQueue;
import com.ricky.mq.client.message.model.BoringTopic;
import com.ricky.mq.client.message.model.TextBoringQueue;
import com.ricky.mq.client.message.model.TextBoringTopic;

/**
 * 抽象的session
 *
 * @author ricky
 * @since 2020.06.18
 */
public abstract class AbstractBoringSession implements BoringSession {

    private static Log LOG = LogFactory.get(BoringSession.class);

    @Override
    public BoringQueue createBoringQueue(String queueName) {
        return createBoringQueue(queueName, Integer.MAX_VALUE);
    }

    @Override
    public BoringQueue createBoringQueue(String queueName, int maxSize) {
        createMsgModel(queueName, maxSize, ClientCommandCode.CREATE_QUEUE);
        return new TextBoringQueue(queueName, maxSize, this);
    }

    @Override
    public BoringTopic createBoringTopic(String topicName) {
        return createBoringTopic(topicName, Integer.MAX_VALUE);
    }

    @Override
    public BoringTopic createBoringTopic(String topicName, int maxSize) {
        createMsgModel(topicName, maxSize, ClientCommandCode.CREATE_TOPIC);
        return new TextBoringTopic(topicName, maxSize, this);
    }

    private void createMsgModel(String modelMsgName, int maxSize, String commendCode) {
        CallbackData callbackData = WaitOrSendMsgHandler.syncSendData(commendCode, ClientMsgModelData.build().setModelMsgName(modelMsgName).setMaxSize(maxSize).setUuid(IdUtil.fastSimpleUUID()));
        if (callbackData.isSuccess()) {
            ServerMsgModelData msgModelData = Convert.convert(ServerMsgModelData.class, callbackData.getBaseData());
            if (msgModelData.isSuccess()) {
                LOG.debug("创建名为：" + modelMsgName + "的消息模型成功o(*￣︶￣*)o");
                return;
            }
        }
        throw new RuntimeException("消息模型创建失败!");
    }

}
